package com.xzc.lease.web.admin.service.impl;

import com.xzc.lease.common.constant.RedisConstant;
import com.xzc.lease.web.admin.mapper.SystemUserMapper;
import com.wf.captcha.SpecCaptcha;
import com.xzc.lease.common.exception.LeaseException;
import com.xzc.lease.common.result.ResultCodeEnum;
import com.xzc.lease.common.utils.JwtUtil;
import com.xzc.lease.model.entity.SystemUser;
import com.xzc.lease.model.enums.BaseStatus;
import com.xzc.lease.web.admin.service.LoginService;
import com.xzc.lease.web.admin.vo.login.CaptchaVo;
import com.xzc.lease.web.admin.vo.login.LoginVo;
import com.xzc.lease.web.admin.vo.system.user.SystemUserInfoVo;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SystemUserMapper systemUserMapper;

    /**
     * 获取图形验证码
     *
     * @return
     */
    public CaptchaVo getCaptcha() {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        //将验证码转为小写，用户输入的数据也转成小写，即可完成不区分大小验证操作
        String code = specCaptcha.text().toLowerCase();
        //设置key的 命名规范
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();
        stringRedisTemplate.opsForValue().set(key, code, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);

        //specCaptcha.toBase64()：经过base64转码得到图片
        return new CaptchaVo(specCaptcha.toBase64(), key);
    }

    /**
     * 登录
     */
    public String login(LoginVo loginVo) {
        //判断用户是否输入验证码
        if (loginVo.getCaptchaCode() == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }

        String code = stringRedisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if (code == null) { //判断验证码是否过期
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }

        //将用户输入的验证码转为小写比较 loginVo.getCaptchaCode().toLowerCase()
        if (!code.equals(loginVo.getCaptchaCode().toLowerCase())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }

        //根据用户名 获取用户信息
        SystemUser systemUser = systemUserMapper.getByUsername(loginVo.getUsername());
        //判断用户是存在
        if (systemUser == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        //判断用户的状态
        if (systemUser.getStatus() == BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //校验用户密码
        if (!systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }

        //创建Jwt令牌返回
        return JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());
    }


    /**
     * 根据userId获取登陆用户个人信息
     * @param userId
     * @return
     */
    public SystemUserInfoVo getLoginUserInfoById(Long userId) {
        //根据id查询用户
        SystemUser systemUser = systemUserMapper.selectById(userId);
        //组装结果返回
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        BeanUtils.copyProperties(systemUser,systemUserInfoVo);
        return systemUserInfoVo;
    }
}
